package JaggSoft.Utilidades;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.border.Border;

public class ImagenFondo implements Border {
    private BufferedImage imagen=null;
    private int x,y,ancho,alto;
    private double ancho_panel,alto_panel;
    public ImagenFondo(String dir) {
        setImagen(dir);
    }
    public void setDimensionesPanel(double anx,double alt){
        this.ancho_panel=anx;
        this.alto_panel=alt;
    }
    public final void setImagen(String dir){
        if(dir.equals(""))
            imagen=null;
        else{
            try {
                this.imagen=ImageIO.read(new File(dir));
            } catch (Exception e) {System.err.println(e.getMessage());}
        }
    }
    private void CalcularDimensionImagen(){
        double ancho_img=(double)imagen.getWidth();
        double alto_img=(double)imagen.getHeight();
        if(ancho_img>ancho_panel||alto_img>alto_panel){
            if(ancho_img-ancho_panel>alto_img-alto_panel){
                ancho=(int)(ancho_panel-70);
                alto=(int)(alto_img*((double)ancho/ancho_img));
                x=70;
                y=(int)((alto_panel-(double)alto)/2);
            }
            else{
                ancho=(int)(ancho_img*(alto_panel/alto_img));
                alto=(int)alto_panel;
                x=(int)((ancho_panel-(double)ancho)/2)+70;
                y=0;
            }
        }
        else{
            x=(int)((ancho_panel-70-ancho_img)/2)+70;
            y=(int)((alto_panel-alto_img)/2);
            ancho=(int)ancho_img;
            alto=(int)alto_img;
        }
    }
    @Override
    public void paintBorder(Component c,Graphics g,int x1,int y1,int x2,int y2) {
        if(imagen!=null){
            CalcularDimensionImagen();
            g.drawImage(imagen,x,y,ancho,alto,null);
        }
    }
    @Override
    public Insets getBorderInsets(Component cmpnt) {
        return new Insets(0,0,0,0);
    }
    @Override
    public boolean isBorderOpaque() {
        return false;
    }
}